<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 2020/6/29
 * Time: 17:20
 */

namespace App\Process;

use EasySwoole\Component\Process\AbstractProcess;
use EasySwoole\EasySwoole\ServerManager;
use Swoole\Process;

class ClearTempCnn extends  AbstractProcess
{
    public function run($arg)
    {
        // TODO: Implement run() method.
        //添加定时器，清理本机无效的连接信息,每隔 10 秒执行一次
        \EasySwoole\Component\Timer::getInstance()->loop(10 * 1000, function () {
            $server = ServerManager::getInstance()->getSwooleServer();
            $start = 0;
            while (true) {
                $conn_list = $server->connection_list($start, 100);
                if (empty($conn_list)) {
                    break;
                }
                $start = end($conn_list);
                foreach ($conn_list as $fd) {
                    $info = $server->getClientInfo($fd);
                    /** 判断此fd 是否是一个有效的 websocket 连接 */
                    if (!isset($info['uid'])||empty($info['uid'])&&(time()-$info['connect_time'])>60) {
                      $server->close($fd);
                    }
                }
            }
        });

    }

    public function onShutDown()
    {
        // TODO: Implement onShutDown() method.
    }

    public function onReceive(string $str, ...$args)
    {
        // TODO: Implement onReceive() method.
    }
}